package com.bto.solar.work.qiniu;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson2.JSONObject;
import com.bto.solar.work.utils.DateUtils;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;

/**
 * @author 王小波
 * @description:   七牛云服务
 * @date 2023/7/24 10:00
 */

@Slf4j
@Component
public class QiNiuService {
    @Value("${qiniu.access-key}")
    private String accessKey;
    @Value("${qiniu.secret-key}")
    private String secretKey;
    @Value("${qiniu.bucket}")
    private String bucket;
    @Value("${qiniu.domains-default}")
    private String domain;
    @Value("${qiniu.callback-url}")
    private String callbackUrl;
    String key = "file key";
    StringMap putPolicy = new StringMap();

    private Auth auth ;

    @PostConstruct
    private void init(){
        auth = Auth.create(accessKey, secretKey);
        putPolicy.put("callbackUrl" , callbackUrl );
        putPolicy.put("callbackBody" , "{\"fname\":\"$(fname)\", \"key\":\"$(key)\", \"fsize\":$(fsize), \"mimeType\":\"$(mimeType)\", \"bucket\":\"$(bucket)\", \"hash\":\"$(etag)\", \"imageInfo\":$(imageInfo), \"ext\":\"$(ext)\", \"fprefix\":\"$(fprefix)\"}");
        putPolicy.put("callbackBodyType" , "application/json");
        putPolicy.put("returnBody", "{\"fname\":\"$(fname)\", \"key\":\"$(key)\", \"fsize\":\"$(fsize)\", \"mimeType\":\"$(mimeType)\", \"bucket\":\"$(bucket)\", \"hash\":\"$(etag)\", \"imageInfo\":$(imageInfo), \"ext\":\"$(ext)\"}");
        putPolicy.put("forceSaveKey" , true);
    }



    /**
    * 获取上传文件的token
     * fileType: video  image  file
    */
    public JSONObject getUploadToken(String orderId , String fileType){
        if("video".equals(fileType)){
            String saves640p = UrlSafeBase64.encodeToString(bucket + ":{$name}.m3u8");
            String saveJpgEntry = UrlSafeBase64.encodeToString(bucket + ":{$name}.jpg");
            List<String> avthumbFop = Arrays.asList("avthumb/m3u8/stripmeta/0/r/30|saveas/" + saves640p, "vframe/jpg/offset/1|saveas/" + saveJpgEntry);
            putPolicy.put("persistentPipeline" , "ym-qrcode");
            putPolicy.put("persistentOps" , String.join(";", avthumbFop));
        }


        JSONObject response = new JSONObject();
        response.put("upToken" , getQiNiuUploadToken(orderId));
        response.put("domain" , domain);

        return response;
    }

    /**
    *   通过订单号，生成长传token
    */
    private String getQiNiuUploadToken(String  orderNo){
        long expireSeconds = 3600;
        String activeFile = SpringUtil.getActiveProfile();
        String suffix = "prod/";
        if(!"prod".equals(activeFile) ){
            suffix = "sit/order/";
        }
        //使用覆盖上传
        String fileKey = suffix+DateUtils.dateTimeNow("yyyy-MM/") +orderNo+"/"+"$(etag)"+"$(ext)";
        putPolicy.put("saveKey" , fileKey);
        return auth.uploadToken(bucket, null , expireSeconds , putPolicy);
    }

    /**
     *  前端自定义路径
     */
    public JSONObject getQiNiuUploadTokenPath(String path){
        long expireSeconds = 3600;
        String activeFile = SpringUtil.getActiveProfile();
        String suffix = "prod";
        if(!"prod".equals(activeFile) ){
            suffix = "sit/"+path+"/";
        }
        putPolicy.put("saveKey" , suffix+"$(etag)"+"$(ext)");

        String uploadToken = auth.uploadToken(bucket, null, expireSeconds, putPolicy);
        JSONObject response = new JSONObject();
        response.put("upToken" , uploadToken);
        response.put("domain" , domain);
        return response;
    }


}
